package com.lp.service;

import cn.hutool.core.util.StrUtil;
import com.lp.websocket.GoBangGame;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class GameService {

    private final Game game = new Game();

    public void addGame(String userName) {
        if (StrUtil.isBlank(game.getAUser())) {
            game.setAUser(userName);
        } else if (StrUtil.isBlank(game.getBUser())) {
            game.setBUser(userName);
        }
        GoBangGame.sendText(userName + "童鞋进入房间;当前房间有:" + (StrUtil.isBlank(game.getAUser()) ? "" : game.getAUser()) + "," + (StrUtil.isBlank(game.getBUser()) ? "" : game.getBUser()));
        ;
    }

    public void playGame(String message, String nickname) {
        if (Objects.equals(nickname, game.getLastUser())) {
            return;
        }
        String[] split = message.split("-");
        int x = Integer.parseInt(split[0]);
        int y = Integer.parseInt(split[1]);
        if (game.getOriData()[y][x] != -1) {
            return;
        }
        //记录步数
        game.setCount(game.getCount() + 1);
        int i = game.getCount() % 2;
        game.getOriData()[y][x] = i;
        int success = game.isSuccess(x, y, i);
        GoBangGame.sendText(message + "-" + i);
        if (success == -1) {
            game.setLastUser(nickname);
        } else {
            if (i == 0) {
                GoBangGame.sendText("alert('白棋获胜,点击确定重新开始游戏!');location.reload(true);");
            } else if (i == 1) {
                GoBangGame.sendText("alert('黑棋获胜,点击确定重新开始游戏!');location.reload(true);");
            }
        }
    }


}
